<?php

require_once 'database/DBConnection.php';
require_once 'Product.php';

class ProductHandler {
	
	private $DBConnection = NULL;
	
	private $m_productTableName = "product";
	
		public function __construct(DBConnection $connection){
		$this->DBConnection = $connection;
	}
	
	// Hämtar alla produkter från tabellen produkter sorterar a - ö
	public function GetAllProducts() {
		
		$ret = array();
                
        $sql = "SELECT * FROM $this->m_productTableName ORDER BY m_productname ASC";
		    
        $stmt = $this->DBConnection->Prepare($sql);
		
		$stmt->execute();
		
		$ret = $this->get($stmt);
		
		$stmt->close();
                
        return $ret; 
	}
	
	// Efter produkt ID
	public function GetProductsById ($a_id) {
		$ret = NULL;
                
        $sql = "SELECT * FROM $this->m_productTableName WHERE product_pk = ? ORDER BY m_productname ASC";
                
        $stmt = $this->DBConnection->Prepare($sql);
		
		$stmt->bind_param("i", $a_id);
		
		$stmt->execute();
		
		$ret = $this->get($stmt);
		
		$stmt->close();
        if(empty($ret)){
        	return ProductView::ProductDoesntExist;	
		}
        return $ret[0]; 
	}
	
	// Efter produkter
	public function GetProductsByCategory ($a_id) {
		$ret = array();
                
        $sql = "SELECT * FROM $this->m_productTableName WHERE m_category = ? ORDER BY m_productname ASC";
                
        $stmt = $this->DBConnection->Prepare($sql);
		
		$stmt->bind_param("s", $a_id);
		
		$stmt->execute();
		
		$ret = $this->get($stmt);
		//------------------------------get_result finkar ej hos webhotellen--------------------------------
			/*$result = $stmt->get_result();
			
			while ($object = $result->fetch_object("Product")) {
				$ret[] = $object;
			}
			*/
			//----------------------------------------------------------------------------------------
		$stmt->close();
                
        return $ret; 
	}
	
	//Behövs då get_result ej funkar----------------------------------------------------------------
	public function get($stmt){
		$ret = array();
		//Alla kolumner i tabellen
		$stmt->bind_result($product_pk, $m_category, $m_productname, $m_price, $m_description, $m_picture);
		
		while ($stmt->fetch()) {
			$product = new Product();
			$product->product_pk = $product_pk;
			$product->m_category =$m_category;
			$product->m_productname=$m_productname;
			$product->m_price = $m_price;
			$product->m_description = $m_description;
			$product->m_picture = $m_picture;
			
        	$ret[] = $product;
    	}
		
		return $ret;
	}
	
}